<template>
  <div class="employee-dashboard">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
          <i class="fa fa-tachometer-alt mr-3 text-primary" :style="{ fontSize: isMobile ? '24px' : '28px' }"></i>
          <h2>员工控制台</h2>
        </div>
        <div class="d-flex align-items-center">
          <div class="weather-info mr-4" :class="{ 'd-none': isMobile }">
            <i class="fa fa-sun text-yellow-500 mr-1"></i>
            <span>{{ weatherInfo.temp }}°C | {{ weatherInfo.description }}</span>
          </div>
          <button @click="logout" class="btn btn-danger" :class="{ 'btn-sm': isMobile }">
            <i class="fa fa-sign-out mr-2"></i>
            <span>{{ isMobile ? '退出' : '退出登录' }}</span>
          </button>
        </div>
      </div>
    </header>

    <!-- 欢迎信息（显示中文职位） -->
    <div class="welcome-section mt-4 p-4 bg-white rounded-lg shadow-sm">
      <div class="d-flex flex-wrap justify-content-between align-items-center">
        <div>
          <p class="mb-1">欢迎回来，<strong>{{ username }}</strong>！</p>
          <p class="text-muted mb-0">
            您的职位是：<span class="badge bg-primary">{{ position }}</span>
          </p>
        </div>
        <div class="mt-2 mt-md-0">
          <div class="d-flex align-items-center">
            <i class="fa fa-calendar-alt text-gray-500 mr-2"></i>
            <span>{{ currentDate }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作按钮 -->
    <div class="quick-actions mt-4 bg-light p-3 rounded-lg shadow-sm">
      <router-link to="/employee/change-password" class="btn btn-secondary" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-key mr-2"></i>
        <span>{{ isMobile ? '改密码' : '修改密码' }}</span>
      </router-link>

      <button v-if="isProjectManager" @click="goToCreateContract" class="btn btn-primary" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-plus mr-2"></i>
        <span>{{ isMobile ? '创建' : '创建合同' }}</span>
      </button>

      <button v-if="isProjectManager" @click="goToSubmitReview" class="btn btn-info" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-clipboard-check mr-2"></i>
        <span>{{ isMobile ? '提交' : '提交与修订' }}</span>
      </button>

      <button v-if="isProjectManager" @click="goToSignContracts" class="btn btn-success" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-file-signature mr-2"></i>
        <span>{{ isMobile ? '签订' : '签订合同' }}</span>
      </button>

      <button v-if="isProjectManager" @click="goToOngoingContracts" class="btn btn-warning" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-spinner fa-spin mr-2"></i>
        <span>{{ isMobile ? '进行中' : '进行中的合同' }}</span>
      </button>

      <button v-if="isProjectManager" @click="goToMyContracts" class="btn btn-success" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-file-contract mr-2"></i>
        <span>{{ isMobile ? '我的合同' : '查看我的合同' }}</span>
      </button>

      <button v-if="isProjectManager" @click="goToArchivedContracts" class="btn btn-dark" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-archive mr-2"></i>
        <span>{{ isMobile ? '归档' : '查看归档合同' }}</span>
      </button>

      <button v-if="isProjectManager" @click="openStatsModal" class="btn btn-info" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-bar-chart mr-2"></i>
        <span>{{ isMobile ? '统计' : '查看统计信息' }}</span>
      </button>

      <button v-if="isLegalSpecialist" @click="goToAuditContracts" class="btn btn-warning" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-gavel mr-2"></i>
        <span>{{ isMobile ? '法务审核' : '法务审核合同' }}</span>
      </button>

      <button v-if="isLegalSpecialist" @click="openLegalStatsModal" class="btn btn-info" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-chart-pie mr-2"></i>
        <span>{{ isMobile ? '法务统计' : '法务审核统计' }}</span>
      </button>

      <button v-if="isFinanceSpecialist" @click="goToAuditContracts" class="btn btn-warning" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-money-bill-wave mr-2"></i>
        <span>{{ isMobile ? '财务审核' : '财务审核合同' }}</span>
      </button>

      <button v-if="isFinanceSpecialist" @click="openFinanceStatsModal" class="btn btn-info" :class="{ 'btn-sm': isMobile }">
        <i class="fa fa-chart-pie mr-2"></i>
        <span>{{ isMobile ? '财务统计' : '财务审核统计' }}</span>
      </button>
    </div>

    <!-- 主要内容区 - 响应式布局 -->
    <div class="main-content mt-4">
      <div class="row gap-4">
        <!-- 左侧：合同统计卡片 -->
        <div :class="isMobile ? 'col-12' : 'col-lg-8'">
          <div class="p-3 bg-white rounded-lg shadow-sm">
            <h3 class="mb-4 pb-2 border-bottom">合同状态统计</h3>
            <div class="stats-cards" v-if="!loading && !errorMessage">
              <div class="row gap-3">
                <div :class="isMobile ? 'col-12' : 'col-md-6'" v-if="isProjectManager">
                  <div class="card bg-light hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">待提交合同</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ pendingCount }}</span>
                            <span class="stat-desc">份合同需要您提交审核</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-primary text-white p-2">
                          <i class="fa fa-paper-plane"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToSubmitReview" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>
                </div>

                <div :class="isMobile ? 'col-12' : 'col-md-6'" v-if="isProjectManager">
                  <div class="card bg-light hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">待修订合同</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ revisionCount }}</span>
                            <span class="stat-desc">份合同需要您修订</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-warning text-dark p-2">
                          <i class="fa fa-edit"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToSubmitReview" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>
                </div>

                <div :class="isMobile ? 'col-12' : 'col-md-6'">
                  <div class="card bg-light hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">已完成合同</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ completedCount }}</span>
                            <span class="stat-desc">份合同已成功完成</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-success text-white p-2">
                          <i class="fa fa-check-circle"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToMyContracts" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>
                </div>

                <div :class="isMobile ? 'col-12' : 'col-md-6'" v-if="isProjectManager">
                  <div class="card bg-warning text-dark hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">进行中的合同</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ ongoingCount }}</span>
                            <span class="stat-desc">份合同正在履行中</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-warning text-dark p-2">
                          <i class="fa fa-spinner"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToOngoingContracts" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>
                </div>

                <div :class="isMobile ? 'col-12' : 'col-md-6'" v-if="isProjectManager">
                  <div class="card bg-dark text-white hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">已归档合同</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ archivedCount }}</span>
                            <span class="stat-desc">份合同已归档</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-gray-600 text-white p-2">
                          <i class="fa fa-archive"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToArchivedContracts" class="card-link mt-3 d-inline-block text-light">查看详情</a>
                    </div>
                  </div>
                </div>

                <div :class="isMobile ? 'col-12' : 'col-md-6'" v-if="isLegalSpecialist || isFinanceSpecialist">
                  <div class="card bg-warning text-dark hover-effect" v-if="isLegalSpecialist">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">待法务审核</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ auditCount }}</span>
                            <span class="stat-desc">份合同需要您审核</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-warning text-dark p-2">
                          <i class="fa fa-gavel"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToAuditContracts" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>

                  <div class="card bg-info text-dark hover-effect" v-if="isFinanceSpecialist">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">待财务审核</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ auditCount }}</span>
                            <span class="stat-desc">份合同需要您审核</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-info text-dark p-2">
                          <i class="fa fa-money-bill-wave"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToAuditContracts" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：日历 -->
        <div :class="isMobile ? 'col-12' : 'col-lg-4'">
          <div class="p-3 bg-white rounded-lg shadow-sm">
            <h3 class="mb-4 pb-2 border-bottom">本月日历</h3>
            <div class="calendar">
              <div class="calendar-header">
                <div class="month-year">{{ currentMonthName }} {{ currentYear }}</div>
              </div>
              <div class="calendar-days">
                <div class="day-header">日</div>
                <div class="day-header">一</div>
                <div class="day-header">二</div>
                <div class="day-header">三</div>
                <div class="day-header">四</div>
                <div class="day-header">五</div>
                <div class="day-header">六</div>

                <div v-for="day in 42" :key="day" class="calendar-day">
                  <div
                      v-if="day <= daysInMonth"
                      :class="{ 'current-day': isCurrentDay(day) }"
                      class="day-number"
                  >
                    {{ day }}
                  </div>
                </div>
              </div>
              <div class="d-flex justify-content-end mt-3">
                <button @click="prevMonth" class="btn btn-sm btn-outline-primary mr-2">
                  <i class="fa fa-chevron-left"></i>
                </button>
                <button @click="nextMonth" class="btn btn-sm btn-outline-primary">
                  <i class="fa fa-chevron-right"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计信息模态框 -->
    <div v-if="showStatsModal || showLegalStatsModal || showFinanceStatsModal" class="stats-modal-overlay">
      <div class="stats-modal" :style="isMobile ? { width: '90%', maxHeight: '90vh' } : { width: '500px' }">
        <div class="stats-modal-header d-flex justify-content-between align-items-center">
          <h3 v-if="showStatsModal">合同统计信息</h3>
          <h3 v-if="showLegalStatsModal">法务审核统计</h3>
          <h3 v-if="showFinanceStatsModal">财务审核统计</h3>
          <button @click="closeStatsModal" class="close-btn">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="stats-modal-body">
          <div class="chart-container" :style="isMobile ? 'height: 240px' : 'height: 300px'">
            <canvas id="modalContractChart"></canvas>
          </div>
          <div class="stats-list" :class="{ 'mobile-stats': isMobile }">
            <div class="stat-item" v-if="showStatsModal">
              <div class="stat-label">待提交合同</div>
              <div class="stat-value">{{ pendingCount }}</div>
            </div>
            <div class="stat-item" v-if="showStatsModal">
              <div class="stat-label">待修订合同</div>
              <div class="stat-value">{{ revisionCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">已完成合同</div>
              <div class="stat-value">{{ completedCount }}</div>
            </div>
            <div class="stat-item" v-if="showStatsModal">
              <div class="stat-label">进行中的合同</div>
              <div class="stat-value">{{ ongoingCount }}</div>
            </div>
            <div class="stat-item" v-if="showStatsModal">
              <div class="stat-label">已归档合同</div>
              <div class="stat-value">{{ archivedCount }}</div>
            </div>
            <div class="stat-item" v-if="showLegalStatsModal || showFinanceStatsModal">
              <div class="stat-label">待审核合同</div>
              <div class="stat-value">{{ auditCount }}</div>
            </div>
            <div class="stat-item" v-if="showLegalStatsModal">
              <div class="stat-label">已通过法务审核</div>
              <div class="stat-value">{{ legalApprovedCount }}</div>
            </div>
            <div class="stat-item" v-if="showLegalStatsModal">
              <div class="stat-label">法务审核驳回</div>
              <div class="stat-value">{{ legalRejectedCount }}</div>
            </div>
            <div class="stat-item" v-if="showFinanceStatsModal">
              <div class="stat-label">已通过财务审核</div>
              <div class="stat-value">{{ financeApprovedCount }}</div>
            </div>
            <div class="stat-item" v-if="showFinanceStatsModal">
              <div class="stat-label">财务审核驳回</div>
              <div class="stat-value">{{ financeRejectedCount }}</div>
            </div>
          </div>
        </div>
        <div class="stats-modal-footer">
          <button @click="closeStatsModal" class="btn btn-primary">
            关闭
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading || legalLoading || financeLoading" class="loading-container mt-4">
      <div class="spinner"></div>
      <p v-if="loading">加载合同统计数据中...</p>
      <p v-if="legalLoading">加载法务审核统计数据中...</p>
      <p v-if="financeLoading">加载财务审核统计数据中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage || legalErrorMessage || financeErrorMessage" class="error-container mt-4">
      <div class="error-message" v-if="errorMessage">
        <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
      </div>
      <div class="error-message" v-if="legalErrorMessage">
        <i class="fa fa-exclamation-circle mr-2"></i>{{ legalErrorMessage }}
      </div>
      <div class="error-message" v-if="financeErrorMessage">
        <i class="fa fa-exclamation-circle mr-2"></i>{{ financeErrorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { computed, ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { Chart } from 'chart.js/auto'

export default {
  name: 'EmployeeDashboard',
  setup() {
    const store = useStore()
    const router = useRouter()

    // 新增：移动端判断
    const isMobile = ref(window.innerWidth < 768)

    // 原有：职位映射表
    const positionMap = {
      'PROJECT_MANAGER': '项目经理',
      'LEGAL_SPECIALIST': '法务专员',
      'FINANCE_SPECIALIST': '财务专员',
      'OTHER': '其他'
    }

    // 用户信息
    const username = computed(() => {
      return store.state.user?.name || '游客'
    })

    // 职位显示为中文
    const position = computed(() => {
      const positionKey = store.state.user?.position
      return positionMap[positionKey] || '未知'
    })

    // 权限判断
    const isProjectManager = computed(() => {
      return store.state.user?.position === 'PROJECT_MANAGER'
    })

    const isLegalSpecialist = computed(() => {
      return store.state.user?.position === 'LEGAL_SPECIALIST'
    })

    const isFinanceSpecialist = computed(() => {
      return store.state.user?.position === 'FINANCE_SPECIALIST'
    })

    // 统计数据（原有）
    const pendingCount = ref(0)
    const revisionCount = ref(0)
    const completedCount = ref(0)
    const ongoingCount = ref(0)
    const archivedCount = ref(0)
    const legalApprovedCount = ref(0)
    const legalRejectedCount = ref(0)
    const financeApprovedCount = ref(0)
    const financeRejectedCount = ref(0)
    const auditCount = ref(0)

    // 日历相关（原有）
    const currentDate = ref('')
    const currentMonth = ref(new Date().getMonth())
    const currentYear = ref(new Date().getFullYear())
    const currentMonthName = ref('')
    const daysInMonth = ref(0)

    // 天气相关（原有）
    const weatherInfo = ref({
      temp: '加载中',
      description: '获取天气中...'
    })

    // 模态框控制（原有）
    const showStatsModal = ref(false)
    const showLegalStatsModal = ref(false)
    const showFinanceStatsModal = ref(false)

    // 图表相关（原有）
    const chartType = ref('project')
    let contractChart = null

    // 加载状态和错误信息（原有）
    const loading = ref(true)
    const legalLoading = ref(false)
    const financeLoading = ref(false)
    const errorMessage = ref('')
    const legalErrorMessage = ref('')
    const financeErrorMessage = ref('')
    const errorCount = ref(0)
    const legalErrorCount = ref(0)
    const financeErrorCount = ref(0)
    const isLoadingAudit = ref(false)

    // 新增：监听窗口尺寸变化
    const handleResize = () => {
      isMobile.value = window.innerWidth < 768
    }

    // 判断是否为当前日期（原有）
    const isCurrentDay = (day) => {
      const now = new Date()
      return (
          day === now.getDate() &&
          currentMonth.value === now.getMonth() &&
          currentYear.value === now.getFullYear()
      )
    }

    // 获取统计数据方法（原有）
    const fetchProjectStats = () => {
      loading.value = true
      errorMessage.value = ''
      errorCount.value = 0
      isLoadingAudit.value = true

      const employeeId = store.state.user?.id
      const employeePosition = store.state.user?.position

      if (!employeeId) {
        errorMessage.value = '用户信息不完整，请重新登录'
        loading.value = false
        isLoadingAudit.value = false
        return
      }

      const pmPromises = []
      if (isProjectManager.value) {
        const pendingPromise = axios.get(`/auth/contracts/pending-submit/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => pendingCount.value = res.data)
            .catch(err => {
              console.error('获取待提交合同数量失败', err)
              errorCount.value++
              handleProjectError()
            })
        pmPromises.push(pendingPromise)

        const revisionPromise = axios.get(`/auth/contracts/pending-revision/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => revisionCount.value = res.data)
            .catch(err => {
              console.error('获取待修订合同数量失败', err)
              errorCount.value++
              handleProjectError()
            })
        pmPromises.push(revisionPromise)

        const ongoingPromise = axios.get(`/auth/contracts/ongoing/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => ongoingCount.value = res.data)
            .catch(err => {
              console.error('获取进行中的合同数量失败', err)
              errorCount.value++
              handleProjectError()
            })
        pmPromises.push(ongoingPromise)

        const archivedPromise = axios.get(`/auth/contracts/archived/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => archivedCount.value = res.data)
            .catch(err => {
              console.error('获取已归档合同数量失败', err)
              errorCount.value++
              handleProjectError()
            })
        pmPromises.push(archivedPromise)
      }

      const completedPromise = axios.get(`/auth/contracts/completed/count`, {
        headers: { 'X-Employee-Id': employeeId }
      })
          .then(res => completedCount.value = res.data)
          .catch(err => {
            console.error('获取已完成合同数量失败', err)
            errorCount.value++
            handleProjectError()
          })

      Promise.all([...pmPromises, completedPromise])
          .then(() => {
            loading.value = false
            initChart('project')
          })
          .catch(() => {
            loading.value = false
          })
    }

    const fetchLegalStats = () => {
      legalLoading.value = true
      legalErrorMessage.value = ''
      legalErrorCount.value = 0

      const employeeId = store.state.user?.id
      const employeePosition = store.state.user?.position

      if (!employeeId) {
        legalErrorMessage.value = '用户信息不完整，请重新登录'
        legalLoading.value = false
        return
      }

      const legalPromises = [
        axios.get(`/auth/contracts/pending-audit/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => auditCount.value = res.data)
            .catch(err => {
              console.error('获取待审核合同数量失败', err)
              legalErrorCount.value++
              handleLegalError()
            }),
        axios.get(`/auth/contracts/legal-approved/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => legalApprovedCount.value = res.data)
            .catch(err => {
              console.error('获取已通过法务审核合同数量失败', err)
              legalErrorCount.value++
              handleLegalError()
            }),
        axios.get(`/auth/contracts/legal-rejected/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => legalRejectedCount.value = res.data)
            .catch(err => {
              console.error('获取法务审核驳回合同数量失败', err)
              legalErrorCount.value++
              handleLegalError()
            })
      ]

      Promise.all(legalPromises)
          .then(() => {
            legalLoading.value = false
            initChart('legal')
          })
          .catch(() => {
            legalLoading.value = false
          })
    }

    const fetchFinanceStats = () => {
      financeLoading.value = true
      financeErrorMessage.value = ''
      financeErrorCount.value = 0

      const employeeId = store.state.user?.id
      const employeePosition = store.state.user?.position

      if (!employeeId) {
        financeErrorMessage.value = '用户信息不完整，请重新登录'
        financeLoading.value = false
        return
      }

      const financePromises = [
        axios.get(`/auth/contracts/pending-audit/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => auditCount.value = res.data)
            .catch(err => {
              console.error('获取待审核合同数量失败', err)
              financeErrorCount.value++
              handleFinanceError()
            }),
        axios.get(`/auth/contracts/finance-approved/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => financeApprovedCount.value = res.data)
            .catch(err => {
              console.error('获取已通过财务审核合同数量失败', err)
              financeErrorCount.value++
              handleFinanceError()
            }),
        axios.get(`/auth/contracts/finance-rejected/count`, {
          headers: { 'X-Employee-Id': employeeId, 'X-Employee-Position': employeePosition }
        })
            .then(res => financeRejectedCount.value = res.data)
            .catch(err => {
              console.error('获取财务审核驳回合同数量失败', err)
              financeErrorCount.value++
              handleFinanceError()
            })
      ]

      Promise.all(financePromises)
          .then(() => {
            financeLoading.value = false
            initChart('finance')
          })
          .catch(() => {
            financeLoading.value = false
          })
    }

    // 错误处理（原有）
    const handleProjectError = () => {
      if (errorCount.value === 1 && !errorMessage.value) {
        errorMessage.value = '获取合同统计数据失败，请稍后再试'
      }
    }

    const handleLegalError = () => {
      if (legalErrorCount.value === 1 && !legalErrorMessage.value) {
        legalErrorMessage.value = '获取法务审核统计数据失败，请稍后再试'
      }
    }

    const handleFinanceError = () => {
      if (financeErrorCount.value === 1 && !financeErrorMessage.value) {
        financeErrorMessage.value = '获取财务审核统计数据失败，请稍后再试'
      }
    }

    // 初始化图表（原有逻辑，新增移动端适配）
    const initChart = (type) => {
      chartType.value = type
      nextTick(() => {
        const ctx = document.getElementById('modalContractChart')

        if (contractChart) {
          contractChart.destroy()
        }

        let labels, data, backgroundColor

        if (type === 'project') {
          labels = ['待提交', '进行中', '已完成', '已归档']
          data = [
            pendingCount.value,
            ongoingCount.value,
            completedCount.value,
            archivedCount.value
          ]
          backgroundColor = [
            '#0d6efd',
            '#ffc107',
            '#28a745',
            '#343a40'
          ]
        } else if (type === 'legal') {
          labels = ['待审核', '已通过', '已驳回']
          data = [
            auditCount.value,
            legalApprovedCount.value,
            legalRejectedCount.value
          ]
          backgroundColor = [
            '#f39c12',
            '#28a745',
            '#e74c3c'
          ]
        } else if (type === 'finance') {
          labels = ['待审核', '已通过', '已驳回']
          data = [
            auditCount.value,
            financeApprovedCount.value,
            financeRejectedCount.value
          ]
          backgroundColor = [
            '#34c6d3',
            '#28a745',
            '#e74c3c'
          ]
        }

        // 新增：图表响应式配置
        contractChart = new Chart(ctx, {
          type: 'doughnut',
          data: {
            labels: labels,
            datasets: [{
              data: data,
              backgroundColor: backgroundColor,
              borderWidth: 0
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'bottom',
                labels: {
                  font: {
                    size: isMobile.value ? 11 : 12
                  }
                }
              }
            },
            cutout: isMobile.value ? '65%' : '70%'
          }
        })
      })
    }

    // 导航方法（原有）
    const goToCreateContract = () => {
      router.push('/contract/create')
    }

    const goToSubmitReview = () => {
      router.push('/employee/submit-review')
    }

    const goToSignContracts = () => {
      router.push('/employee/pending-sign')
    }

    const goToOngoingContracts = () => {
      router.push('/employee/ongoing-contracts')
    }

    const goToMyContracts = () => {
      router.push('/employee/my-contracts')
    }

    const goToArchivedContracts = () => {
      router.push('/employee/archived-contracts')
    }

    const goToAuditContracts = () => {
      router.push('/employee/audit-contracts')
    }

    const logout = () => {
      localStorage.removeItem('user')
      localStorage.removeItem('role')
      store.commit('setUser', null)
      router.push('/login')
    }

    // 模态框控制（原有）
    const openStatsModal = () => {
      showStatsModal.value = true
      showLegalStatsModal.value = false
      showFinanceStatsModal.value = false
      fetchProjectStats()
    }

    const openLegalStatsModal = () => {
      showStatsModal.value = false
      showLegalStatsModal.value = true
      showFinanceStatsModal.value = false
      fetchLegalStats()
    }

    const openFinanceStatsModal = () => {
      showStatsModal.value = false
      showLegalStatsModal.value = false
      showFinanceStatsModal.value = true
      fetchFinanceStats()
    }

    const closeStatsModal = () => {
      showStatsModal.value = false
      showLegalStatsModal.value = false
      showFinanceStatsModal.value = false
    }

    // 日期和天气（原有）
    const updateDateInfo = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth()
      const day = now.getDate()
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']

      currentDate.value = `${year}年${month + 1}月${day}日 ${days[now.getDay()]}`
      currentMonth.value = month
      currentYear.value = year
      currentMonthName.value = monthNames[month]
      daysInMonth.value = new Date(year, month + 1, 0).getDate()
    }

    const fetchWeather = () => {
      const weatherData = {
        temp: Math.floor(Math.random() * 30) + 10,
        description: ['晴天', '多云', '小雨', '阴天'][Math.floor(Math.random() * 4)]
      }
      weatherInfo.value = weatherData
    }

    // 月份切换（原有）
    const prevMonth = () => {
      currentMonth.value = (currentMonth.value - 1 + 12) % 12
      if (currentMonth.value === 11) {
        currentYear.value--
      }
      const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
      currentMonthName.value = monthNames[currentMonth.value]
      daysInMonth.value = new Date(currentYear.value, currentMonth.value + 1, 0).getDate()
    }

    const nextMonth = () => {
      currentMonth.value = (currentMonth.value + 1) % 12
      if (currentMonth.value === 0) {
        currentYear.value++
      }
      const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
      currentMonthName.value = monthNames[currentMonth.value]
      daysInMonth.value = new Date(currentYear.value, currentMonth.value + 1, 0).getDate()
    }

    // 生命周期（原有逻辑，新增窗口监听）
    onMounted(() => {
      updateDateInfo()
      fetchWeather()
      fetchProjectStats()

      // 新增：窗口大小监听
      window.addEventListener('resize', handleResize)

      const date = new Date()
      if (date.getDate() === 1) {
        updateDateInfo()
      }

      setInterval(() => {
        updateDateInfo()
        fetchWeather()
      }, 24 * 60 * 60 * 1000)
    })

    watch([
      () => store.state.user?.id,
      () => store.state.user?.position
    ], () => {
      fetchProjectStats()
      if (isLegalSpecialist.value) fetchLegalStats()
      if (isFinanceSpecialist.value) fetchFinanceStats()
    })

    onUnmounted(() => {
      if (contractChart) {
        contractChart.destroy()
      }
      // 新增：移除窗口监听
      window.removeEventListener('resize', handleResize)
    })

    return {
      // 原有返回值
      username, position,
      isProjectManager, isLegalSpecialist, isFinanceSpecialist,
      pendingCount, revisionCount, completedCount, auditCount, ongoingCount, archivedCount,
      legalApprovedCount, legalRejectedCount,
      financeApprovedCount, financeRejectedCount,
      loading, legalLoading, financeLoading,
      errorMessage, legalErrorMessage, financeErrorMessage,
      goToCreateContract, goToSubmitReview, goToSignContracts,
      goToOngoingContracts, goToMyContracts, goToArchivedContracts, goToAuditContracts, logout,
      currentDate, currentMonthName, currentYear, daysInMonth,
      weatherInfo, prevMonth, nextMonth,
      showStatsModal, showLegalStatsModal, showFinanceStatsModal,
      openStatsModal, openLegalStatsModal, openFinanceStatsModal, closeStatsModal,
      isCurrentDay,
      // 新增：移动端标识
      isMobile
    }
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.employee-dashboard {
  padding: 20px;
  max-width: 100%;
}

.header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.header-content {
  width: 100%;
}

.welcome-section {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.quick-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 10px 18px;
  border-radius: 6px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
  font-size: 14px;
  border: none;
}

.btn-primary { background-color: #3498db; color: white; box-shadow: 0 4px 6px rgba(52, 152, 219, 0.2); }
.btn-secondary { background-color: #7f8c8d; color: white; box-shadow: 0 4px 6px rgba(127, 140, 141, 0.2); }
.btn-info { background-color: #34c6d3; color: white; box-shadow: 0 4px 6px rgba(52, 198, 211, 0.2); }
.btn-warning { background-color: #f39c12; color: #212529; box-shadow: 0 4px 6px rgba(243, 156, 18, 0.2); }
.btn-danger { background-color: #e74c3c; color: white; box-shadow: 0 4px 6px rgba(231, 76, 60, 0.2); }
.btn-success { background-color: #27ae60; color: white; box-shadow: 0 4px 6px rgba(39, 174, 96, 0.2); }
.btn-dark { background-color: #2c3e50; color: white; box-shadow: 0 4px 6px rgba(44, 62, 80, 0.2); }

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.main-content .row {
  display: flex;
  gap: 20px;
}

.main-content .col-lg-8 {
  flex: 1;
}

.main-content .col-lg-8 > div {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.stats-cards .card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  margin-bottom: 15px;
  background-color: white;
}

.stats-cards .card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stats-cards .card-body {
  padding: 18px;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  margin-right: 10px;
  display: block;
}

.stat-desc {
  font-size: 14px;
  color: #6c757d;
  display: block;
}

.card-link {
  color: #3498db;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s;
}

.card-link:hover {
  color: #2980b9;
  text-decoration: underline;
}

.main-content .col-lg-4 {
  flex: 0 0 300px;
  max-width: 300px;
}

.main-content .col-lg-4 > div {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.calendar {
  padding: 15px;
}

.calendar-header {
  margin-bottom: 15px;
  text-align: center;
}

.month-year {
  font-size: 18px;
  font-weight: 600;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.day-header {
  text-align: center;
  font-weight: 500;
  padding: 5px;
  color: #6c757d;
}

.calendar-day {
  text-align: center;
  padding: 5px;
  min-height: 30px;
}

.day-number {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.current-day {
  background-color: #3498db;
  color: white;
  font-weight: 600;
}

.stats-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.stats-modal {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  max-width: 90%;
  max-height: 80vh;
  overflow: auto;
}

.stats-modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
}

.stats-modal-body {
  padding: 20px;
}

.stats-modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #e9ecef;
  text-align: right;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #6c757d;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #343a40;
}

.chart-container {
  margin-bottom: 20px;
}

.stats-list {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.stat-item {
  padding: 10px;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.stat-label {
  font-size: 14px;
  color: #6c757d;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
}

.loading-container {
  text-align: center;
  padding: 50px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 50px;
}

.error-message {
  color: #e74c3c;
  font-size: 16px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f8d7da;
  display: inline-block;
}

.icon-circle {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hover-effect {
  transition: transform 0.3s, box-shadow 0.3s;
}

.hover-effect:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 新增：移动端适配样式 */
@media (max-width: 767px) {
  .employee-dashboard {
    padding: 10px;
  }

  .header {
    padding: 10px 15px;
    margin-bottom: 15px;
  }

  .quick-actions {
    gap: 8px;
    padding: 10px;
  }

  .btn {
    padding: 8px 12px;
    font-size: 13px;
    flex: 1 0 auto;
    min-width: 45%;
  }

  .btn-sm {
    padding: 6px 10px;
    font-size: 12px;
  }

  .main-content .row {
    flex-direction: column;
    gap: 15px;
  }

  .col-12 {
    width: 100%;
    flex: none;
  }

  .stats-cards .card-body {
    padding: 15px;
  }

  .stat-number {
    font-size: 24px;
  }

  .stat-desc {
    font-size: 13px;
  }

  .calendar {
    padding: 10px 0;
  }

  .month-year {
    font-size: 16px;
  }

  .calendar-days {
    gap: 3px;
  }

  .day-header {
    padding: 3px;
    font-size: 12px;
  }

  .day-number {
    width: 26px;
    height: 26px;
    line-height: 26px;
    font-size: 12px;
  }

  .stats-modal-body {
    padding: 15px;
  }

  .mobile-stats {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .stat-item {
    padding: 8px;
  }

  .stat-label {
    font-size: 13px;
  }

  .stat-value {
    font-size: 16px;
  }

  .loading-container, .error-container {
    padding: 30px 15px;
  }

  .spinner {
    width: 36px;
    height: 36px;
  }
}

/* 辅助类（新增） */
.d-none {
  display: none !important;
}

.col-12 {
  width: 100%;
}
</style>